package cn.dynamic.view.controller;

import cn.dynamic.view.entity.ResultVO;
import cn.dynamic.view.entity.ViewEntity;
import cn.dynamic.view.service.LoggingReadComponent;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
public class ViewController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(ViewController.class);

    private DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Resource
    private LoggingReadComponent readComponent;

    /**
     * 端点日志查看
     * @param viewEntity
     * @return
     */
    @PostMapping(value = "/endpoint/view")
    public ResultVO getUrlData(@RequestBody ViewEntity viewEntity) {
        try {
            HttpResponse execute = HttpRequest.get(viewEntity.getUrl()).execute();
            if (execute.getStatus() == 200) {
                String body = execute.body();
                return success(body);
            } else {
                String body = execute.body();
                return error(body);
            }
        }catch (Throwable throwable) {
            logger.error("error info!!", throwable);
            return error("error info!! info:" + throwable.getMessage());
        }
    }

    /**
     * 读取指定路径监听文件查看
     * @return
     */
    @PostMapping(value = "/logging/view")
    public ResultVO getLoggingData(@RequestBody ViewEntity viewEntity) {
        String path = viewEntity.getPath();
        String startTime = viewEntity.getStartTime();
        String endTime = viewEntity.getEndTime();
        Integer limit = viewEntity.getLimit();
        try {
            if (limit == null) {
                limit = 0;
            }
            Date sTime = null;
            Date eTime = null;
            if (startTime != null && !"".equals(startTime)) {
                sTime = new Date(LocalDateTime.parse(startTime, formatter).toInstant(OffsetDateTime.now().getOffset()).toEpochMilli());
            }
            if (endTime != null && !"".equals(endTime)) {
                eTime = new Date(LocalDateTime.parse(endTime, formatter).toInstant(OffsetDateTime.now().getOffset()).toEpochMilli());
            }
            if (sTime != null && eTime != null && sTime.getTime() > eTime.getTime()) {
                return error("时间区间异常！");
            }
            Map<String, Object> data = readComponent.readLogging(path, sTime, eTime, limit.intValue());

            return success(data);
        } catch (Throwable throwable) {
            logger.error("error info!!", throwable);
            return error("error info!! info:" + throwable.getMessage());
        }
    }

    /**
     * 解析Dynamic-Tp的日志monitor生成文件
     * @return
     */
    @PostMapping(value = "/logging/parseMonitor")
    public ResultVO parseMonitorFile(@RequestPart(value = "file") MultipartFile multipartFile) {
        try {
            byte[] bytes = multipartFile.getBytes();
            String tmpFile = readComponent.createTmpFile(bytes);
            Map<String, Object> data = readComponent.readLogging(tmpFile, null, null, 0);
            new File(tmpFile).delete();
            return success(data);
        } catch (Throwable throwable) {
            logger.error("error info!!", throwable);
            return error("error info!! info:" + throwable.getMessage());
        }
    }

}
